#!/usr/bin/perl
#
use strict;
my $input = $ARGV[0];
my $outDir = $ARGV[1];
my $action = $ARGV[2];

sub catFileLine {
  my $outPut = "";
  my ($file) = $_[0];
  my ($altern) = $_[1];
  if ( -f $file ) {
    open FH, $file;
    $outPut = <FH>;
    close FH;
    chomp($outPut);  # remove the newline
  }
  if ( "$outPut" eq "" ) {
    $outPut = $altern;
  }
  return $outPut;
}

sub printFileLine {
  my $file = "$_[0]";
  my $varName = "$_[1]";
  my $rest = $_[2];
  my $oldVal = catFileLine($file);
# print ("Update file=$file, varName=$varName, content:$rest<BR>");
  if (( -f $file ) and ( $oldVal eq $rest )) {
    # update the access time (= touch), if a file is unchanged.
    my $now = time;
    if ( $varName ne "noTouch" ) {
      utime $now, $now, $file;
    }
  } else {
    if ( "$rest" eq "" ) {
      # remove file if it exists (don't display message if it doesn't.).
      if ( -f $file ) {
        unlink ($file);
        print("$varName is verwijderd, oud:$oldVal<BR>");
      }
    } elsif ( "$varName" eq "append" ) {
#     print("writing to $file<BR>.");
      open(OUT, ">>$file") || die "cannot append $file: $!";
      print OUT $rest;
      close(OUT);
    } else {
      open(OUT, ">$file") || die "cannot create $file: $!";
      if (( "$varName" ne "quiet" ) and ( $varName ne "noTouch" )) {
        print("$varName is gewijzigd, oud:$oldVal nieuw:$rest<BR>");
      }
      print OUT $rest;
      close(OUT);
    }
  }
}

if (( -f $input ) and ( -d $outDir )) {
  open( IN, $input );
  my @lines = <IN>;
  close IN;
  foreach my $line (@lines) {
    my ( $mac, $type, $info ) = split(' ', $line, 3);
    if ( $type eq "(hex)" ) {
      my $dmac = lc($mac);
      $dmac =~ s/-/:/g;
#     print("dmac:$dmac, info:$info.\n");
      if ( $action eq "import" ) {
        system(" mkdir $outDir/$dmac ");
        printFileLine("$outDir/$dmac/vendor","verdor-$dmac",$info);
      }
    }
  }
} else {
  print("Usage: progje <oui.txt> <output_dir> test | import
  use the official oui file from http://standards.ieee.org/develop/regauth/oui/oui.txt\n");
}
